<template>
  <view class="bg-white flex flex-col">
    <nav-bar title="后厨小票设置" color="white" bg-color="black" show-back></nav-bar>
    <view class="content">
      <view class="flex">
        <view class="flex-1 p-10rpx">
          <view class="p-10rpx text-base text-gray-500 font-bold">小票模板</view>
          <view class="col-box">
            <view class="w-fit m-auto my-10rpx flex">
              <u-button icon="plus" color="#55a4fb" icon-color="white" @click="addNewTempalte">新增模板</u-button>
            </view>

            <view
              :class="['ticket', 'mb-10rpx', currentTemplateId == tick.id ? 'used' : '']"
              v-for="tick in templateList"
              :key="tick.id"
            >
              <comTicket :info="tick.print" :editor="editor" />

              <view class="w-fit m-auto mt-10rpx flex">
                <u-text v-if="currentTemplateId == tick.id" color="#3c9cff" text="- 当前模板 -"></u-text>
                <u-button v-else color="#55a4fb" plain @click="usePrintTemplate(tick)">使用该模板</u-button>
                <view class="w-10rpx"></view>
                <!-- 默认模板 和当前模板，不可删除 -->
                <u-button
                  color="red"
                  plain
                  v-if="tick.id != 1 && currentTemplateId != tick.id"
                  @click="delPrintTemplate(tick)"
                  >删除</u-button
                >
              </view>
              <view class="text-gray-400 text-sm text-center mt-10rpx" v-if="tick.id == 1">默认模板，不可删除</view>
            </view>
          </view>
        </view>
        <view class="flex-1 p-10rpx">
          <view class="p-10rpx text-base text-gray-500 font-bold">模板编辑</view>

          <view class="col-box">
            <!-- 模板编辑区 -->
            <view class="ticket current">
              <comTicket :info="editor" :editor="editor" />
            </view>
          </view>

          <view @click="printTest" class="text-base py-10rpx text-center text-gray-500"> -打印测试-</view>
        </view>
        <view class="flex-auto">
          <view class="p-10rpx text-base text-gray-500 font-bold">选择显示的内容</view>
          <view class="col-box bg-white">
            <view v-for="(item, index) in currFields" :key="index" class="mt-10rpx">
              <view class="p-5rpx text-base text-gray-500 font-bold">{{ item.name }}</view>
              <!-- {{ item }} -->
              <view>
                <u-grid col="3" :border="false">
                  <u-grid-item v-for="(field, fi) in item.fields" :key="field.name">
                    <!-- {{ field }} -->
                    <view
                      @click="changeFieldUsed(field)"
                      :class="['field-item', hasField(field.name) ? 'has-selected' : '']"
                    >
                      <text class="field-item-text">{{ field.value }}</text>
                      <view v-if="field.canEdit" @click.stop="editFixedValue(field)" :class="['field-item-edit-btn']">
                        <u-icon name="edit-pen-fill" color="white"></u-icon>
                      </view>
                    </view>
                  </u-grid-item>
                </u-grid>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>

  <resultPopup ref="refresultPopup">
    <template #default="{ result }">
      <input class="ref-compopup-content-input" type="text" v-model="result.content" placeholder="请输入内容" />
      <!-- <u-input v-model="model" placeholder="请输入内容" clearable /> -->
    </template>
  </resultPopup>
</template>
<script setup>
import { onMounted, ref, reactive, computed, nextTick } from "vue";
import { printorder, printStart, printStartByDevice } from "./print-utils";
import { /* cashiersTemplate, */ fields, sourceDate } from "./template";
import { useStore } from "vuex";
import comTicket from "./com-ticket.vue";
import resultPopup from "@/components/common-popup/result-popup.vue";
const store = useStore();

const editor = ref([]);
const tempconfig = ref({}); // 当前模板在字段配置
const templateList = ref([]);
const currentTemplateId = computed(() => store.getters.currentRearTemplateId);
const currentTemplate = computed({
  get: () => store.getters.currentRearTemplate,
  set: (val) => {},
});
// const currFields = computed(() => store.getters.currentFields);
const printInstance = ref("");

const ticketType = "kitchen";

const cashiersTemplate = computed(() => {
  return store.getters.printTemplate.filter((item) => {
    return item.type == ticketType || item.type == "all";
  });
});

// 判断当前使用模板中是否有该字段
const hasField = computed(() => {
  return (field) => {
    return currentTemplate.value.useFields.includes(field);
  };
});

onMounted(() => {
  init();
});

const init = async () => {
  // 当前模板编辑
  const { source, data } = printorder(sourceDate, currentTemplate.value); // 解构 去引用
  editor.value = source;
  printInstance.value = data;

  await nextTick();

  // 循环创建模板预览
  const tempList = [];

  for (const temp of cashiersTemplate.value) {
    const { source } = printorder(sourceDate, temp); // 解构 去引用
    tempList.push({
      id: temp.id,
      print: source,
    });
  }
  await nextTick();
  templateList.value = tempList.reverse();
  // console.log("templateList = ", templateList.value, tempList);

  // 更新字段
  updateFields();
};

const printTest = async () => {
  // console.log("最后的Arg = printInstance.value", printInstance.value);
  // 查询本地设备列表中类型为 前台 打印的设备
  const printerDevices = store.getters.usbPrinterListRear;
  if (Array.isArray(printerDevices)) {
    if (printerDevices.length == 0) return uni.showToast({ title: "请先设置后厨设备", icon: "none" });
    // 下单打印小票 需要根据 【打印设置】 中的设备需要打印的设备类型，再从
    // 本地设备列表中获取对应类型的设备id，然后调用打印接口
    for (const device of printerDevices) {
      try {
        await printStartByDevice(printInstance.value, device.path);
      } catch (error) {
        console.error(`设备 ${device.name} 打印小票失败`, error);
      }
    }
  } else {
    // 打印
    await printStart(printInstance.value);
  }
  // printStart(printInstance.value);
};

const delPrintTemplate = (tick) => {
  // uni.showModal({
  //   title: "提示",
  //   content: `确定要删除模板吗？`,
  //   success: (res) => {
  //     if (res.confirm) {
  //       store.dispatch("delPrintTemplate", tick);
  //     }
  //   },
  // });
  // console.log("tick = ", tick);
  store.commit("print/deleteTemplate", tick.id);
  // 修改之后需要重新生成当前模板/模板列表
  init();
};

const usePrintTemplate = async (tick) => {
  console.log("tick = ", tick);

  // 对当前模板进行编辑

  // 根据 tick.id 获取模板数据，并更新当前编辑的模板
  const temp = store.getters.printTemplate.find((item) => item.id == tick.id);
  const { source, data } = printorder(sourceDate, temp); // 解构 去引用

  // console.log("usePrintTemplate/printOrderUtils = ", {source, data}, temp.useFields);
  editor.value = source;
  printInstance.value = data;

  store.commit("print/useTemplate", { id: tick.id, type: ticketType });
  // 修改之后需要重新生成当前模板/模板列表
  init();
};

const changeFieldUsed = (field) => {
  store.commit("print/editTemplateField", { name: field.name, isUsed: !field.isUsed, type: ticketType });
  // 修改之后需要重新生成当前模板/模板列表
  init();
};

//
const addNewTempalte = () => {
  store.commit("print/addTemplateByModule", ticketType);
  // 修改之后需要重新生成当前模板/模板列表
  init();
};

// const CSNPrinter = uni.requireNativePlugin('CSNPrinter')

const refresultPopup = ref(null);
const editFixedValue = (field) => {
  refresultPopup.value.open({
    confirmText: "修改",
    title: "编辑文字",
    showIcon: false,
    content: field.value,
    onConfirm: (opts) => {
      console.log("opts = ", opts);
      // 获取修改后的值 “content”
      field.value = opts.content;
      // 更新配置 fixedValue 设定该字段的固定值
      store.commit("print/editTemplateFixedValue", {
        id: currentTemplate.value.id, // 当前编辑模板id
        fixedValue: { name: field.name, fixed: opts.content }, //修改的数据
      });
      // 修改之后需要重新生成当前模板/模板列表
      init();
    },
  });
};

// 获取字段编辑区 显示字段
const getFieldText = (field) => {
  // 如果字段与 cashiersTemplate.value.fixedConfig 存在固定值，则显示固定值，否则显示 field.value
  const fixedConfig = cashiersTemplate.value.find((item) => item.id == currentTemplate.value.id)?.fixedConfig;
  if (!fixedConfig || fixedConfig.length == 0) return field.value;
  // 查找 field.name 是否在 fixedConfig[index].name 中存在
  const index = fixedConfig.findIndex((item) => item.name == field.name);
  if (index > -1) {
    return fixedConfig[index].fixed;
  }
  return field.value;
};

// 当前可使用字段数据

const currFields = reactive([]);
// 更新字段
const updateFields = () => {
  currFields.length = 0;
  for (const item of fields) {
    const result = [];
    for (const field of item.fields) {
      result.push({
        ...field,
        value: getFieldText(field),
      });
    }
    // console.log("result = ", result);
    currFields.push({
      ...item,
      fields: result,
    });
  }
};
</script>
<style lang="scss" scoped>
.content {
  // height: 100%;
  justify-content: baseline;
  background-color: white;

  .col-box {
    padding: 10rpx;
    background-color: #f9f9f9;
    height: auto;
    max-height: 80vh;
    overflow: scroll;
  }

  ::v-deep .u-row {
    // height: 100%;
    align-items: flex-start !important;
  }

  ::v-deep .u-col {
    border-right: 1px solid #eee;
    // height: 100%;
    flex: auto;
    // padding: 10rpx;
    justify-content: baseline !important;
  }

  .ticket {
    background-color: white;
    font-size: 9rpx;
    padding: 10rpx;
    // margin: 10px;
    box-sizing: border-box;
    width: fit-content;
    margin: auto;
    margin-bottom: 10rpx;
    border-radius: 5px;

    &.current {
      box-shadow: 0px 0px 10rpx #b9dcff;
    }

    &.used {
      border: #3c9cff 2px solid;
    }
  }

  .field-item {
    border: 2px solid #929292;
    color: #929292;
    font-size: 10rpx;
    width: calc(100% - 20rpx);
    padding: 5rpx 2rpx;
    display: flex;
    text-align: center;
    justify-content: center;
    margin-top: 5rpx;
    border-radius: 3rpx;
    font-weight: bold;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;

    .field-item-text {
      white-space: nowrap;
      text-overflow: ellipsis;
      /* max-width: 5em; */
      display: block;
      width: 6em;
      text-align: center;
      overflow: hidden;
    }

    &.has-selected {
      border: 2px solid #3c9cff;
      color: #3c9cff;
    }

    .field-item-edit-btn {
      width: 20rpx;
      height: 20rpx;
      border-radius: 50%;
      background-color: #3c9cff;
      color: white;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 10rpx;
      margin-left: 5rpx;
      position: absolute;
      right: 0rpx;
      top: 0rpx;
    }
  }
}

.ref-compopup-content-input {
  padding: 8rpx;
  border: 2px solid #3c9cff;
  color: #3c9cff;
  font-weight: bold;
  border-radius: 2rpx;
}
</style>
